package cn.xz.mxxz.activity

import android.app.DatePickerDialog
import android.graphics.Color
import android.os.Handler
import android.util.Log
import android.widget.DatePicker
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import cn.xz.mxxz.R
import cn.xz.mxxz.adapter.*
import cn.xz.mxxz.base.BaseActivity
import cn.xz.mxxz.base.BaseApplication
import cn.xz.mxxz.bean.*
import cn.xz.mxxz.databinding.ActivityDreamBinding
import cn.xz.mxxz.dialog.AllNowDialog
import cn.xz.mxxz.dialog.LeaderDialog
import cn.xz.mxxz.net.ControlDevice
import cn.xz.mxxz.net.OkHttpUtil
import cn.xz.mxxz.net.OkhttpResponseHandle
import cn.xz.mxxz.util.AppHelper
import cn.xz.mxxz.util.EventBusUtils
import cn.xz.mxxz.util.ToastUtil
import java.util.*
import kotlin.collections.ArrayList


/**
 * 梦想印记
 * */
class DreamActivity : BaseActivity<ActivityDreamBinding>(R.layout.activity_dream){

    //标识符
    private var mTag = 0
    //设备信息
    private var mDevice: DeviceList? = null
    //带队领导数据
    private val mDDL: ArrayList<LeaderData> = arrayListOf()
    //已选带队领导
    private val mDDS: ArrayList<String> = arrayListOf()
    //随从领导
    private val mSCL: ArrayList<LeaderData> = arrayListOf()
    //已选随从领导
    private val mSCS: ArrayList<String> = arrayListOf()
    //历史弹窗列表
    private val mYear: ArrayList<LeaderData> = arrayListOf()
    //类别1适配器
    var mDreamTAdapter1: DreamTAdapter? = null
    //类别2适配器
    var mDreamTAdapter2: DreamTAdapter? = null
    //已选择领导适配器
    var mShowLeaderAdapter: LeaderShowAdapter? = null
    //印记列表适配器
    var mSearchListAdapter: SearchListAdapter? = null
    //历史弹窗适配器
    var mDialogAdapter: DialogAdapter? = null
    //当前是否全选印记列表
    var selectYjAll = false
    //当前界面请求标识
    private val mWsType = "dq_imprint_web"

    override fun initData() {
        //获取当前设备信息
        mTag = intent.getIntExtra(CommonLib.JUMP_TYPE, -1)
        if (mTag != -1){
            mDevice = ControlDevice.getThisDevice(mTag)
            if (CommonLib.MY_LOCAL_IP.isNotEmpty() && mDevice != null){
                mDevice!!.ip = CommonLib.MY_LOCAL_IP
            }
            mDevice!!.ip = CommonLib.WEB_IP
            mDevice!!.port = CommonLib.WEB_PORT
        }
        //如果数据异常直接退出
        if (mTag == -1 || mDevice == null){
            ToastUtil.show("当前数据异常")
            finish()
        }else{
            //设置标题
            mDataBind.tvTitle.text = ControlDevice.getDeviceName(mTag)
            //获取类别1
            initGetLB()
            //获取类别2
            initGetLB2()
            //获取带队领导
            initDD()
            //获取随从领导
            initSC()
            //显示已选择的领导
            showLeader()
            //获取年份
            getYear()
        }
    }

    private fun initGetLB(){
        val mUrl = "http://${mDevice!!.ip}:${mDevice!!.port}/business_dj/app/mxyj/listMxyjType"
        OkHttpUtil.get(this, mUrl,
            DreamTitleBean::class.java, object : OkhttpResponseHandle<DreamTitleBean?>() {
                override fun onSuccess(response: DreamTitleBean?) {
                    if (response != null && response.data != null && response.data.isNotEmpty()){
                        response.data.add(0, DreamTitle(0,"全部","0","sys_dj_mxyj_type",true))
                        val ms = LinearLayoutManager(this@DreamActivity)
                        ms.orientation = LinearLayoutManager.HORIZONTAL
                        mDataBind.rvType1.layoutManager = ms
                        mDreamTAdapter1 = DreamTAdapter()
                        mDreamTAdapter1?.setOnItemClickListener { adapter, view, position ->
                            val data = mDreamTAdapter1!!.data as ArrayList<DreamTitle>
                            data.forEach {
                                it.select = false
                                if (it.dictValue == data[position].dictValue){
                                    it.select = true
                                }
                            }
                            mDreamTAdapter1?.notifyDataSetChanged()
                        }
                        mDataBind.rvType1.adapter = mDreamTAdapter1
                        mDreamTAdapter1?.setList(response.data)
                    }

                }
            })

    }

    private fun initGetLB2(){
        val mUrl = "http://${mDevice!!.ip}:${mDevice!!.port}/business_dj/app/mxyj/listMxyjType2"
        OkHttpUtil.get(this, mUrl,
            DreamTitleBean::class.java, object : OkhttpResponseHandle<DreamTitleBean?>() {
                override fun onSuccess(response: DreamTitleBean?) {
                    if (response != null && response.data != null && response.data.isNotEmpty()){
                        response.data.add(0, DreamTitle(0,"全部","0","sys_dj_mxyj_type2",true))
                        val ms = LinearLayoutManager(this@DreamActivity)
                        ms.orientation = LinearLayoutManager.HORIZONTAL
                        mDataBind.rvType2.layoutManager = ms
                        mDreamTAdapter2 = DreamTAdapter()
                        mDreamTAdapter2?.setOnItemClickListener { adapter, view, position ->
                            val data = mDreamTAdapter2!!.data as ArrayList<DreamTitle>
                            data.forEach {
                                it.select = false
                                if (it.dictValue == data[position].dictValue){
                                    it.select = true
                                }
                            }
                            mDreamTAdapter2?.notifyDataSetChanged()
                        }
                        mDataBind.rvType2.adapter = mDreamTAdapter2
                        mDreamTAdapter2?.setList(response.data)
                    }

                }
            })
    }

    private fun initDD(){
        val mUrl = "http://${mDevice!!.ip}:${mDevice!!.port}/business_dj/app/mxyj/listTeamLeader"
        OkHttpUtil.get(this, mUrl,
            LeaderBean::class.java, object : OkhttpResponseHandle<LeaderBean?>() {
                override fun onSuccess(response: LeaderBean?) {
                    if (response != null && response.data.isNotEmpty()){
                        response.data.forEach {
                            mDDL.add(LeaderData(it))
                        }
                    }
                }
            })

    }

    private fun initSC(){
        val mUrl = "http://${mDevice!!.ip}:${mDevice!!.port}/business_dj/app/mxyj/listAccompanyLeader"
        OkHttpUtil.get(this, mUrl,
            LeaderBean::class.java, object : OkhttpResponseHandle<LeaderBean?>() {
                override fun onSuccess(response: LeaderBean?) {
                     if (response != null && response.data.isNotEmpty()){
                         response.data.forEach {
                             mSCL.add(LeaderData(it))
                         }
                     }
                }
            })

    }

    override fun initEvent() {
        //退出
        mDataBind.tvFinish.setOnClickListener {
            finish()
        }
        //首页
        mDataBind.tvBack.setOnClickListener {
            OkHttpUtil.postUrlWebID(mDevice!!.ip,mDevice!!.port,"redirectPage",1,mWsType)
        }
        //历史变迁
        mDataBind.tvRightHst.setOnClickListener {
            OkHttpUtil.postUrlWebID(mDevice!!.ip,mDevice!!.port,"redirectPage",2,mWsType)
        }
        //全部时间
        mDataBind.tvTimeAll.setOnClickListener {
            setTime(true)
        }
        //开始时间
        mDataBind.tvKsTime.setOnClickListener {
            //获取实例，包含当前年月日
            val calendar: Calendar = Calendar.getInstance()
            val dialog = DatePickerDialog(
                this, object :DatePickerDialog.OnDateSetListener{
                    override fun onDateSet(
                        view: DatePicker?,
                        year: Int,
                        month: Int,
                        dayOfMonth: Int
                    ) {
                        setTime(false)
                        Log.e("TAG", "onDateSet: ---${year},${month+1},${dayOfMonth}")
                        mDataBind.tvKsTime.text = "${year}-${month+1}-${dayOfMonth}"
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MARCH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
            dialog.show()
        }
        //结束时间
        mDataBind.tvEndTime.setOnClickListener {
            //获取实例，包含当前年月日
            val calendar: Calendar = Calendar.getInstance()
            val dialog = DatePickerDialog(
                this, object :DatePickerDialog.OnDateSetListener{
                    override fun onDateSet(
                        view: DatePicker?,
                        year: Int,
                        month: Int,
                        dayOfMonth: Int
                    ) {
                        setTime(false)
                        Log.e("TAG", "onDateSet: ---${year},${month+1},${dayOfMonth}")
                        mDataBind.tvEndTime.text = "${year}-${month+1}-${dayOfMonth}"
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MARCH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
            dialog.show()
        }
        //带队领导
        mDataBind.etDdName.setOnClickListener {
            if (mDDL.isNotEmpty()){
                LeaderDialog.newInstance(mDDL,true,object :LeaderDialog.OnClickListener{
                    override fun onYes(mLeader: ArrayList<String>) {
                        mDDS.clear()
                        mDDS.addAll(mLeader)
                        showLeader()
                    }

                    override fun onNo() {
                    }

                }).show(this.supportFragmentManager,"LeaderDialog1234")
            }
        }
        //随从领导
        mDataBind.etSc.setOnClickListener {
            if (mSCL.isNotEmpty()){
                LeaderDialog.newInstance(mSCL,false,object :LeaderDialog.OnClickListener{
                    override fun onYes(mLeader: ArrayList<String>) {
                        mSCS.clear()
                        mSCS.addAll(mLeader)
                        showLeader()
                    }

                    override fun onNo() {
                    }

                }).show(this.supportFragmentManager,"LeaderDialog543")
            }
        }
        //清空筛选
        mDataBind.tvLeftC.setOnClickListener {
            //类别1
            if (mDreamTAdapter1 != null){
                val data = mDreamTAdapter1!!.data as ArrayList<DreamTitle>
                data.forEachIndexed { index, dreamTitle ->
                    dreamTitle.select = index == 0
                }
                mDreamTAdapter1!!.notifyDataSetChanged()
            }
            //类别2
            if (mDreamTAdapter2 != null){
                val data = mDreamTAdapter2!!.data as ArrayList<DreamTitle>
                data.forEachIndexed { index, dreamTitle ->
                    dreamTitle.select = index == 0
                }
                mDreamTAdapter2!!.notifyDataSetChanged()
            }
            //时间范围
            setTime(true)
            //清空领导
            mDDL.forEach {
                it.select = false
            }
            mSCL.forEach {
                it.select = false
            }
            mDDS.clear()
            mSCS.clear()
            showLeader()
        }
        //确定筛选
        mDataBind.tvLeftS.setOnClickListener {
            getSX()
        }
        //展示选择内容
        mDataBind.tvShowSelect.setOnClickListener {
            if (mSearchListAdapter != null){
                //获取当前选择内容
                val mData = mSearchListAdapter!!.data as ArrayList<SimpleData>
                var mSelect = ""
                mData.forEachIndexed { index, simpleData ->
                    if (simpleData.select){
                        if (mSelect == ""){
                            mSelect = "${simpleData.id}"
                        }else{
                            mSelect = mSelect + ",${simpleData.id}"
                        }
                    }
                }
                Log.e("TAG", "initEvent: sdsdsas--选择印记--${mSelect}", )
                val params = OpenBeanShowAll.Params()
                params.showAll = 0
                params.ids = mSelect
                OkHttpUtil.postUrlWebShowAll(mDevice!!.ip,mDevice!!.port,"updateWall",params,mWsType)

            }

        }
        //展示全部内容
        mDataBind.tvShowAll.setOnClickListener {
            //直接发命令
            val params = OpenBeanShowAll.Params()
            params.showAll = 1
            params.ids = ""
            OkHttpUtil.postUrlWebShowAll(mDevice!!.ip,mDevice!!.port,"updateWall",params,mWsType)
        }
        //全选印记列表
        mDataBind.llcSAll.setOnClickListener {
            if (mSearchListAdapter != null) {
                //获取当前选择内容
                val mData = mSearchListAdapter!!.data as ArrayList<SimpleData>
                if (selectYjAll){
                    //全不选
                    mData.forEach {
                        it.select = false
                    }
                }else{
                    //全选
                    mData.forEach {
                        it.select = true
                    }
                }
                mSearchListAdapter!!.notifyDataSetChanged()
                selectYjAll = !selectYjAll
                shoeYJListAll()
            }
        }
        //关闭弹窗
        mDataBind.tvDisDialog.setOnClickListener {
            disDialog()
        }
        //上一页
        mDataBind.tvSY.setOnClickListener {
            OkHttpUtil.postUrlWebType(mDevice!!.ip,mDevice!!.port,"albumControl",1,mWsType)
        }
        //下一页
        mDataBind.tvXY.setOnClickListener {
            OkHttpUtil.postUrlWebType(mDevice!!.ip,mDevice!!.port,"albumControl",2,mWsType)
        }

    }

    //印记列表
    private fun setYJList(mData: ArrayList<SimpleData>){
            if (mSearchListAdapter != null){
                mSearchListAdapter?.setList(mData)
            }else{
                val ms = LinearLayoutManager(BaseApplication.getContext())
                ms.orientation = LinearLayoutManager.VERTICAL
                mDataBind.rvSearchList.layoutManager = ms
                mSearchListAdapter = SearchListAdapter()
                mSearchListAdapter?.setOnItemClickListener { adapter, view, position ->
                    val data = adapter.data as ArrayList<SimpleData>
                    data[position].select = !data[position].select
                    adapter.notifyDataSetChanged()

                    selectYjAll = false
                    shoeYJListAll()

                }
                mDataBind.rvSearchList.adapter = mSearchListAdapter
                mSearchListAdapter?.setList(mData)
            }

    }

    //是否全选印记列表
    private fun shoeYJListAll(){
        var mD = AppHelper.getDrawable(R.mipmap.icon_select)
        var mC = "#000000"
        if (selectYjAll){
            mD = AppHelper.getDrawable(R.mipmap.icon_select_1)
            mC = "#548BF7"
        }
        mDataBind.tvSAll.setTextColor(Color.parseColor(mC))
        mDataBind.ivSAll.setImageDrawable(mD)
    }

    //已选领导
    private fun showLeader(){
        val mAllLeader: ArrayList<String> = arrayListOf()
        mAllLeader.add("带队领导")
        if (mDDS.isNotEmpty()){
            mAllLeader.addAll(mDDS)
        }else{
            mAllLeader.add("未选择")
        }
        mAllLeader.add("陪同和随从领导")
        if (mSCS.isNotEmpty()){
            mAllLeader.addAll(mSCS)
        }else{
            mAllLeader.add("未选择")
        }
        if (mShowLeaderAdapter != null){
            mShowLeaderAdapter!!.setList(mAllLeader)
        }else{
            val ms = LinearLayoutManager(BaseApplication.getContext())
            ms.orientation = LinearLayoutManager.VERTICAL
            mDataBind.rvLdList.layoutManager = ms
            mShowLeaderAdapter = LeaderShowAdapter()
            mDataBind.rvLdList.adapter = mShowLeaderAdapter
            mShowLeaderAdapter?.setList(mAllLeader)
        }
    }

    private fun getYear(){
        val mUrl = "http://${mDevice!!.ip}:${mDevice!!.port}/business_dj/app/mxyj/listYear"
        OkHttpUtil.get(this, mUrl,
            LeaderBean::class.java, object : OkhttpResponseHandle<LeaderBean?>() {
                override fun onSuccess(response: LeaderBean?) {
                    if (response != null && response.data.isNotEmpty()){
                        response.data.forEach {
                            mYear.add(LeaderData(it))
                        }
                        showDialog()
                    }
                }
            })
    }

    //弹窗气泡
    private fun showDialog(){
        val ms = object : GridLayoutManager(this, 3) {
            //禁止上下滑动
            override fun canScrollVertically(): Boolean {
                return true
            }
        }
        mDataBind.rvDialog.layoutManager = ms
        mDialogAdapter = DialogAdapter()
        mDialogAdapter?.setOnItemClickListener { adapter, view, position ->
            val data = adapter.data as ArrayList<LeaderData>
            data.forEach {
                it.select = false
                if (it.name == data[position].name){
                    //先关闭弹窗
                    disDialog()
                    //延迟
                    Handler().postDelayed({
                        //打开弹窗
                        OkHttpUtil.postUrlWebID(mDevice!!.ip,mDevice!!.port,"openWindow",it.name.toInt(),mWsType)
                    }, 800)
                    it.select = true
                }
            }
            adapter.notifyDataSetChanged()
        }
        mDataBind.rvDialog.adapter = mDialogAdapter
        mDialogAdapter?.setList(mYear)
    }

    //关闭历史弹窗
    private fun disDialog(){
        OkHttpUtil.postUrlWebID(mDevice!!.ip,mDevice!!.port,"openWindow",0,mWsType)
        if (mDialogAdapter != null){
            val data = mDialogAdapter!!.data as ArrayList<LeaderData>
            data.forEach {
                it.select = false
            }
            mDialogAdapter!!.notifyDataSetChanged()
        }
    }

    //时间选择
    private fun setTime(b: Boolean){
        if (b){
            mDataBind.tvTimeAll.setTextColor(Color.parseColor("#FFFFFF"))
            mDataBind.tvTimeAll.background = AppHelper.getDrawable(R.drawable.bg_1890ff_5)
            mDataBind.tvKsTime.text = "开始日期"
            mDataBind.tvEndTime.text = "结束日期"
        }else{
            mDataBind.tvTimeAll.setTextColor(Color.parseColor("#000000"))
            mDataBind.tvTimeAll.background = null
        }
    }

    //确定筛选
    private fun getSX(){
        //ids？？？
        var mIDS = ""
        //获取类别1
        var mType1 = ""
        if (mDreamTAdapter1 != null){
            val data = mDreamTAdapter1!!.data as ArrayList<DreamTitle>
            if (data != null && data.isNotEmpty()){
                if (data[0].select){
                    /*data.forEachIndexed { index, dreamTitle ->
                        if (index != 0){
                            if (mType1 == ""){
                                mType1 = dreamTitle.dictValue
                            }else{
                                mType1 = mType1 + "," + dreamTitle.dictValue
                            }
                        }

                    }*/
                }else{
                    data.forEach {
                        if (it.select){
                            mType1 = it.dictValue
                        }
                    }
                }
            }
        }
        //获取类别2
        var mType2 = ""
        if (mDreamTAdapter2 != null){
            val data = mDreamTAdapter2!!.data as ArrayList<DreamTitle>
            if (data != null && data.isNotEmpty()){
                if (data[0].select){
                    /*data.forEachIndexed { index, dreamTitle ->
                        if (index != 0){
                            if (mType2 == ""){
                                mType2 = dreamTitle.dictValue
                            }else{
                                mType2 = mType2 + "," + dreamTitle.dictValue
                            }
                        }

                    }*/
                }else{
                    data.forEach {
                        if (it.select){
                            mType2 = it.dictValue
                        }
                    }
                }
            }
        }
        //带队领导
        var mDDStr = ""
        if (mDDS.isNotEmpty()){
            mDDS.forEachIndexed { index, s ->
                if (mDDStr == ""){
                    mDDStr = s
                }else{
                    mDDStr = mDDStr + "," +s
                }
            }
        }
        //随从领导
        var mSCStr = ""
        if (mSCS.isNotEmpty()){
            mSCS.forEachIndexed { index, s ->
                if (mSCStr == ""){
                    mSCStr = s
                }else{
                    mSCStr = mSCStr + "," + s
                }
            }
        }
        Log.e("TAG", "initEvent上传:-----类型1-${mType1},类型2-${mType2},开始时间-${mDataBind.tvKsTime.text.toString()}," +
                "结束时间-${mDataBind.tvEndTime.text.toString()},带队领导-${mDDStr},随从领导-${mSCStr}" )
        //获取印记列表
        val mUrl = "http://${mDevice!!.ip}:${mDevice!!.port}/business_dj/app/mxyj/listMxyjSimple?" +
                "ids=${mIDS}&types=${mType1}&type2s=${mType2}&eventDateStart=${mDataBind.tvKsTime.text}&eventDateEnd=${mDataBind.tvEndTime.text}" +
                "&teamLeaders=${mDDStr}&accompanyLeaders=${mSCStr}"
        OkHttpUtil.get(this, mUrl,
            SimpleBean::class.java, object : OkhttpResponseHandle<SimpleBean?>() {
                override fun onSuccess(response: SimpleBean?) {
                    if (response != null){
                        if (response.data != null && response.data.isNotEmpty()){
                            setYJList(response.data)
                        }else{
                            selectYjAll = false
                            shoeYJListAll()
                            val mNData: ArrayList<SimpleData> = arrayListOf()
                            setYJList(mNData)
                        }
                    }
                }
            })

    }
}
